package com.yj.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yj.model.Admin;
import com.yj.model.Student;
import com.yj.model.Teacher;
import com.yj.utils.Md5Class;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends BaseAction<Object> {

	private static final long serialVersionUID = 1L;

	public String login() {
		HttpServletRequest hsRequest = ServletActionContext.getRequest();
		Integer role = Integer.parseInt((String)hsRequest.getParameter("role"));
        Integer username = Integer.parseInt((String)hsRequest.getParameter("username"));
        String password = Md5Class.stringToMd5((String)hsRequest.getParameter("password"));
        if(role == 1) {
        	Student student = new Student();
        	student.setId(username);
        	student.setPassword(password);
			student = (Student) userService.login(student, role);
			if(student == null) {
				return ERROR;
			}
			session.put("student", student);
			request.put("allCourses", courseService.query());
			request.put("message", "登陆成功!");
			return "studentLogin";

        }else if(role == 2) {
        	Teacher teacher = new Teacher();
        	teacher.setId(username);
        	teacher.setPassword(password);
        	teacher = (Teacher) userService.login(teacher, role);
			if(teacher == null) {
				return ERROR;
			}
			session.put("teacher", teacher);
			request.put("message", "登陆成功!");
        	return "teacherLogin";
        }else if(role == 3) {
        	Admin admin = new Admin();
        	admin.setId(username);
        	admin.setPassword(password);
        	admin = (Admin) userService.login(admin, role);
        	if(admin == null) {
				return ERROR;
			}
        	session.put("admin", admin);
			request.put("allAcademy", academyService.query());
			request.put("message", "登陆成功!");
        	return "adminLogin";
        }else {
    		return ERROR;
        }
	}
	
	public String logout() {
		if(session.get("student") != null) {
			session.remove("student");
		}
		if(session.get("teacher") != null) {
			session.remove("teacher");
		}
		if(session.get("admin") != null) {
			session.remove("admin");
		}
		return "logout";
	}
}
